package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.pojo.Link;
import com.itheima.pojo.LinkVO;
import com.itheima.pojo.Result;
import com.itheima.pojo.StatusCode;
import com.itheima.service.LinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/link")
public class LinkController {

    @Autowired
    private LinkService linkService;

    //1.添加链接
    @PostMapping("/add")
    public Result add(@RequestBody LinkVO linkVO){

        try {
            linkService.add(linkVO);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(StatusCode.ERROR,"插入失败");
        }
        return new Result(StatusCode.OK,"插入成功");
    }

    //2.删除链接
    @PostMapping("/delete")
    public  Result delete(@RequestBody LinkVO linkVO){

        try {
            linkService.delete(linkVO);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(StatusCode.ERROR,"删除失败");
        }
        return new Result(StatusCode.OK,"删除成功");
    }

    //3. 更新链接
    @PostMapping("/edit")
    public Result edit(@RequestBody LinkVO linkVO){

        try {
            linkService.edit(linkVO);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(StatusCode.ERROR,"更新失败");
        }
       return new Result(StatusCode.OK,"更新成功");
    }

    //4.获取链接列表
    @PostMapping("/getList")
    public Map<String,Object> getList(@RequestBody LinkVO linkVO){

        PageInfo<Link> pageInfo = linkService.getList(linkVO);

        Map<String,Object> result= new HashMap<>();

        Map<String,Object> recordsMap = new HashMap<>();
        recordsMap.put("records",pageInfo.getList());
        recordsMap.put("total",pageInfo.getTotal());
        recordsMap.put("size",linkVO.getPageSize());
        recordsMap.put("current",linkVO.getCurrentPage());
        recordsMap.put("orders",null);
        recordsMap.put("optimizeCountSql",true);
        recordsMap.put("isSearchCount",true);

        result.put("code","success");
        result.put("data",recordsMap);
        return result;
    }

    //5. 链接置顶
    @PostMapping("/stick")
    public Result stick(@RequestBody LinkVO linkVO){

        try {
            linkService.stick(linkVO);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(StatusCode.ERROR,"该链接已经在顶上");
        }
        return new Result(StatusCode.OK,"置顶成功");
    }

}
